package com.fenda.qq;

import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.Vector;

/**
 * QQ聊天界面
 */
public class QQChatFrame {

	public static void main(String[] args) {
		start(null, null);
	}

	public static void start(String user,String friend) {

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		JFrame frame = new JFrame("与"+friend+"的聊天");
		frame.setBounds(500, 300, 800, 600);

		JPanel mainPanel = new JPanel();
		//mainPanel.setBorder(new LineBorder(Color.BLACK,5));
		frame.setContentPane(mainPanel);

		JPanel chatLogPanel = new JPanel();
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setSize(770,380);
		scrollPane.setBorder( new LineBorder(Color.BLACK));

		chatLogPanel.setBounds(2, 2, 780, 400);
		chatLogPanel.setBorder(new LineBorder(Color.RED));
		chatLogPanel.setLayout(null);
		chatLogPanel.add(scrollPane);
		mainPanel.add(chatLogPanel);

		JPanel chatPanel = new JPanel();
		chatPanel.setBounds(2, 405, 680, 150);
		chatPanel.setBorder(new LineBorder(Color.RED));
		JTextArea tf = new JTextArea();
		chatPanel.add(tf);
		chatPanel.setLayout(new GridLayout());
		mainPanel.add(chatPanel);

		JPanel btnPanel = new JPanel();
		btnPanel.setBounds(685, 405, 95, 150);
		btnPanel.setBorder(new LineBorder(Color.RED));
		JButton btn = new JButton("发送");
		int length = 1;
		Vector v = new Vector();
		btn.addActionListener(new ActionListener() {//按钮点击事件
			@Override
			public void actionPerformed(ActionEvent e) {
				String content = tf.getText();//发给对方的
				//自己的展示
				String show = user + " " + sdf.format(new Date()) + "：" + content;
				QQResponse response = QQClient.sendMsg(user,friend,show);
				System.out.println(response);
				v.add(show);
				JList list = new JList(v);
				scrollPane.setViewportView(list);
				chatLogPanel.repaint();
			}
		});
		btnPanel.add(btn);
		btnPanel.setLayout(new GridLayout());
		mainPanel.add(btnPanel);


		//弹出好友框之前需要加载聊天信息
		QQResponse response = QQClient.findChatLog(user,friend);
		if(response.getSuccess()){
			if(response.getChatLogs() != null){//如果没有聊天记录
				for(String log : response.getChatLogs()){
					v.add(log);
				}
				JList list = new JList(v);
				scrollPane.setViewportView(list);
				chatLogPanel.repaint();
			}
		}
		frame.setLayout(null);//不使用系统布局方式
		//frame.setLayout(new FlowLayout());//流式布局
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭窗体退出程序
		frame.setVisible(true);
	}

}
